<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Cart;
use App\Models\MallFullReduction;
use App\Models\MallProductStock;
use App\Models\Merchant;
use App\Models\Product;
use App\Services\FullReductionService;
use App\Services\MallOrderService;
use App\Services\ZeroJoinCheckService;
use Illuminate\Http\Request;

class CartController extends BaseController
{

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        Cart::whereIn('id', $arr_id)->delete();
        return $this->success([]);
    }

    private function _checkStockEmpty($product, $is_specs, $specs_str, $buy_num) {
        if ($is_specs) {
            $stock = MallProductStock::where('product_id', $product->id)->where('key', $specs_str)->value('stock') ?: 0;
            if ($stock < $buy_num) {
                return true;
            }
        } else {
            if ( $product->stock < $buy_num) {
                return true;
            }
        }
        return false;
    }

    //{"specs_1":"黑色","specs_2":"M","amount":10,"vip_amount":9.9,"stock":100,"weight":1}
    public function store(Request $request) {
        $this->validate($request, [
            'product_id' => 'required',
            'buy_num' => 'required',
            'action' => 'required|in:update,create'
        ]);
        $user = $this->getUser();
        $user_id = $user->id;
        $input = $request->input();
        $action = $input['action'];

        $product = Product::find($input['product_id']);
        if (!$product || $product->on_status != 1)
            return $this->failed('商品已下架');

        $left_amount = 0;
        if ($input['action'] == 'update') {
            if (!isset($input['id']))
                return $this->failed('购物车ID缺失');
            $cart_one = Cart::find($input['id']);
            if (!$cart_one)
                return $this->failed('不存在购物车ID');

            if ($input['buy_num'] >= 10)
                return $this->failed('商品一次最多购买10件');

            $is_empty = $this->_checkStockEmpty($product, $product->is_specs, $cart_one->specs_str, $input['buy_num']);
            if ($is_empty)
                return $this->failed('该商品库存不足!');


            $cart_one->buy_num = $input['buy_num'];
            $cart_one->save();
        } else {
            $is_direct = $request->input('is_direct', 0);
            $input['producer_id'] = $product->producer_id;

            $cart_one = Cart::where('user_id', $user_id)->where('is_direct', $is_direct)->where('product_id', $input['product_id']);
            if (!empty($input['specs_info'])) {
                $input['specs_str'] =  MallOrderService::specsKey($input['specs_info']);
                $input['is_specs'] = 1;
                $cart_one = $cart_one->where('specs_str', $input['specs_str']);
            } else {
                $input['specs_str'] = '';
            }
            $cart_one = $cart_one->first();
            if ($is_direct) {
                $cart_one && $cart_one->delete();
            }

            if ($is_direct || !$cart_one) {
                $input['user_id'] = $user_id;
                unset($input['action']);
                if (!$product->is_specs) {
                    $input['is_specs'] = 0;
                }

                if ($input['buy_num'] >= 10)
                    return $this->failed('商品一次最多购买10件');

                $is_empty = $this->_checkStockEmpty($product, $product->is_specs, $input['specs_str'], $input['buy_num']);
                if ($is_empty)
                    return $this->failed('该商品库存不足!');

                $cart_one = Cart::create($input);
            }
            else {
                $cart_one->buy_num += $input['buy_num'];

                if ($cart_one->buy_num >= 10)
                    return $this->failed('商品一次最多购买10件');

                $is_empty = $this->_checkStockEmpty($product, $product->is_specs, $cart_one->specs_str, $cart_one->buy_num);
                if ($is_empty)
                    return $this->failed('库存不足!');
                $cart_one->save();
            }

            //参加满减包邮
            $left_amount = 0;
            if ($product->is_full_reduction)
                $left_amount = FullReductionService::handle($product->producer_id, $user);
        }
        //购物车总数
        $cart_total = Cart::where('is_direct', 0)->where('user_id', $user_id)->count();
        return $this->success(['action' => $action, 'total' => $cart_total, 'cart_id' => $cart_one->id, 'left_amount' => $left_amount], '操作成功');
    }


    public function index(Request $request) {
        $user = $this->getUser();
        $input = $request->input();
        if (isset($input['cart_ids'])) {
            $arr_cart_ids = explode(",", $input['cart_ids']);
        } else {
            $arr_cart_ids = [];
        }
        $zero_product_id = $input['zero_product_id'] ?? 0;
        $zero_product = null;

        $is_direct = $request->input('is_direct', 0);
        $list = Cart::withCertain('product', ['is_full_reduction', 'title', 'fare', 'specs_detail_info', 'amount', 'vip_amount', 'is_specs', 'image_url'])
            ->when(!empty($arr_cart_ids), function ($q) use($arr_cart_ids){
            $q->whereIn('id', $arr_cart_ids);
        })->where('user_id', $this->getUserId())->where('is_direct', $is_direct)
            ->orderBy('id', 'desc')
            ->paginate(per_page(99));

        foreach ($list as $key => &$val) {
            $product = $val->product;
            $val->is_valid = false;
            if ($product) {
                $val->is_valid = true;
                if ($product->is_specs) {
                    $amount = $product->specs_detail_info[$val->specs_str]['amount'] ?? '';
                    if (!$amount) {
                        Cart::where('id', $val->id)->delete();
                        unset($list[$key]);
                        continue;
                    }
                    $vip_amount = $product->specs_detail_info[$val->specs_str]['vip_amount'] ?? '';
                } else {
                    $amount = $product->amount_yuan;
                    $vip_amount = $product->vip_amount_yuan;
                }
                $val->unit_amount = $val->amount_yuan = !$user->is_vip ? $amount : $vip_amount;
                $val->title = $product->title; //目前取这里
                $val->image_url = $product->image_url;
            }
        }

        //运费
        $fare = 0;
        if (isset($input['is_show_fare'])) {
            $group_list = $list->groupBy('producer_id')->toArray();
            foreach ($group_list as $producer_id => $item) {
                //判断是否满足满减包邮
                $is_satify_free_fare = false;
                $reduction_paid_amount = 0;
                foreach ($item as $val) {
                    $product = $val['product'];
                    if (!$product['is_full_reduction'])
                        continue;

                    if ($product['is_specs']) {
                        $match_val = $product['specs_detail_info'][$val['specs_str']];
                        $amount = $match_val['amount'] ?? '';
                        if (!$amount)
                            continue;
                        $vip_amount = $match_val['vip_amount'] ?? '';
                        $amount_yuan = !$user->is_vip ? $amount : $vip_amount;
                    } else {
                        $amount_yuan = format_yuan(!$user->is_vip ? $product['amount'] : $product['vip_amount']);
                    }
                    $reduction_paid_amount += $amount_yuan * $val['buy_num'] * 100;
                }
                //获取满减包邮
                $amount = MallFullReduction::where('merchant_id',$producer_id)->value('amount');
                if ($amount !== null) {
                    $amount = $amount * 100;
                    $is_satify_free_fare = ($amount - $reduction_paid_amount) >0 ? false : true;
                }

                $arr_product = array_column($item, 'product');
                $arr_fare = array_column($arr_product, 'fare');
                if (!$is_satify_free_fare && !empty($arr_fare))
                    $fare += max($arr_fare);

                if ($is_satify_free_fare) {
                    if ($zero_product_id) {
                        $ret = ZeroJoinCheckService::handle($user);
                        if ($ret['status'] == 1) {
                            $temp = Product::select(['title', 'image_url', 'id', 'producer_id'])->find($zero_product_id);
                            if (array_key_exists($temp->producer_id, $group_list)) {
                                $zero_product = $temp;
                            }
                        }
                    }
                }

            }
        }
        return $this->paginate($list, compact('fare', 'zero_product'));
    }

    public function index_v2() {
        $user = $this->getUser();
        $list = Cart::withCertain('product', ['is_full_reduction', 'title', 'fare', 'specs_detail_info', 'amount', 'vip_amount', 'is_specs', 'image_url'])
            ->withCertain('reduction', ['amount', 'merchant_id'])
            ->where('user_id', $this->getUserId())->where('is_direct', 0)
            ->orderBy('id', 'desc')
            ->paginate(per_page(99));

        $collect = [];
        foreach ($list as $key => &$val) {
            $product = $val->product;
            $val->is_valid = false;
            if ($product) {
                $val->is_valid = true;
                if ($product->is_specs) {
                    $amount = $product->specs_detail_info[$val->specs_str]['amount'] ?? '';
                    if (!$amount) {
                        Cart::where('id', $val->id)->delete();
                        unset($list[$key]);
                        continue;
                    }
                    $vip_amount = $product->specs_detail_info[$val->specs_str]['vip_amount'] ?? '';
                } else {
                    $amount = $product->amount_yuan;
                    $vip_amount = $product->vip_amount_yuan;
                }
                $val->unit_amount = $val->amount_yuan = !$user->is_vip ? $amount : $vip_amount;
            }
        }

        $group_list = $list->groupBy('producer_id');
        //判断是否满减包邮
        foreach ($group_list as $producer_id => $item) {
            $first = $item->first();
            $temp['producer_id'] = $producer_id;
            $temp['fac_title'] = Merchant::find($producer_id)->fac_title;
            $temp['full_reduction_amount'] = $first->reduction->amount ?? 0;
            $buy_amount = 0;
            $item_temp = [];
            foreach ($item as $child) {
                if ($child->product->is_full_reduction)
                    $buy_amount += $child->amount_yuan * $child->buy_num;

                $item_temp[] = [
                    'id' => $child->id,
                    'product_id' => $child->product_id,
                    'buy_num' => $child->buy_num,
                    'created_at' => $child->created_at,
                    'specs_info_show' => $child->specs_info_show,
                    'is_specs' => $child->product->is_specs,
                    'unit_amount' => $child->unit_amount,
                    'amount_yuan' => $child->amount_yuan,
                    'is_full_reduction' => $child->product->is_full_reduction,
                    'title' => $child->product->title,
                    'image_url' => $child->product->image_url[0] ?? null
                ];
            }
            $temp['has_buy_amount'] = $buy_amount;
            $temp['item'] = $item_temp;
            $collect[] = $temp;
        }
        return $this->success($collect);
    }


}

